import os
import docx
import xlwt
from win32com import client

# Function to convert .doc to .docx
def convert_to_docx(file_path):
    word = client.Dispatch('Word.Application')
    doc = word.Documents.Open(file_path)
    doc.SaveAs(file_path + "x", 12)  # 12 stands for docx format
    doc.Close()
    word.Quit()
workbook = xlwt.Workbook()
style = xlwt.XFStyle()
style.num_format_str = '@'
keywords = ["题目","分部：","学习中心：","专业","入学时间","学号","姓名","指导教师","论文完成日期","作者签名","日期","作者签名","日期"]  # 请将关键词替换为您需要的关键词
sheet = workbook.add_sheet('提取数据')

# 写入文件名作为第一列
sheet.write(0, 0, "文件名")

for i, keyword in enumerate(keywords):
    sheet.write(0, i+1, keyword)  # 从第二列开始写入关键词

# Replace 'folder_path' with the path of your folder
folder_path = 'D:\pytest\paperinputs'  # 请将"your_folder_path"替换为自己的文件夹路径

# Iterate through the files in the folder
for file_name in os.listdir(folder_path):
    if  file_name.endswith(".doc"):
        file_path = os.path.join(folder_path, file_name)
        convert_to_docx(file_path)
                  
        os.chmod(file_path, 0o644)  # 更新文件权限,将只读文件权限设置成可编辑

        os.remove(file_path)  # Delete the original .doc file

# 重新遍历文件夹，提取所有.docx格式文件的数据
row = 1  # 从第二行开始写入数据
for filename in os.listdir(folder_path):
    if filename.endswith(".docx"):
        doc_path = os.path.join(folder_path, filename)
        doc = docx.Document(doc_path)

        # 写入文件名
        sheet.write(row, 0, filename)

        # 提取文档内容
        for i, keyword in enumerate(keywords):
            text = ""
            for paragraph in doc.paragraphs:
                if keyword.replace(" ", "") in paragraph.text.replace(" ", ""):
                    text = paragraph.text.split(keyword)[-1].strip()
                    text = text.replace(":", "").replace("：", "")  
                    sheet.write(row, i+1, text, style)
                    break  

        row += 1

for i in range(len(keywords) + 1):
    sheet.col(i).width = 256 * 20  # 设置列宽

workbook.save('extracted_data.xls')
